package com.attendancesystem.controller;

import com.attendancesystem.model.Lecture;
import com.attendancesystem.service.LectureService;
import com.attendancesystem.util.JDBCUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;




import jakarta.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.Map;

@WebServlet(name = "UpdateLectureController", value = "/UpdateLectureController")
public class UpdateLectureController extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final LectureService lectureService=new LectureService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        Map<String, Object> requestData = objectMapper.readValue(request.getReader(), Map.class);

        try {
//            pstmt.setString(1, (String) requestData.get("className"));
//            pstmt.setTimestamp(2, java.sql.Timestamp.valueOf(
//                    ((String) requestData.get("lectureTime")).replace("T", " ") + ":00"));
//            pstmt.setString(3, (String) requestData.get("classroom"));
//            pstmt.setString(4, (String) requestData.get("courseTitle"));
//            pstmt.setString(5, (String) requestData.get("courseId"));


            // 1. 解析请求数据到Lecture对象
            Lecture lecture = new Lecture();
            lecture.setCourseId(Integer.parseInt((String) requestData.get("courseId")));
            lecture.setClassName((String) requestData.get("className"));
            lecture.setLectureTime(LocalDateTime.parse((String) requestData.get("lectureTime")));
            lecture.setClassroom((String) requestData.get("classroom"));
            lecture.setSummary((String) requestData.get("summary"));
            System.out.println("lecture:"+lecture);

            // 2. 调用Service层

            lectureService.updateLecture(lecture);

            // 3. 返回成功响应
            response.getWriter().write("{\"status\":\"success\"}");

        } catch (SQLException e) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("{\"status\":\"error\",\"message\":\""+e.getMessage()+"\"}");
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"status\":\"error\",\"message\":\"服务器异常\"}");
        }


    }
}
